import {asyncRoutes, constantRoutes, componentMap} from '@/router'
import {getRoutes, getPermissions} from '@/api/auth'


/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 * 未用到
 */
// function hasPermission(roles, route) {
//   if (route.meta && route.meta.roles) {
//     return roles.some(role => route.meta.roles.includes(role))
//   } else {
//     return true
//   }
// }

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 * 未用到
 */
// export function filterAsyncRoutes(routes, roles) {
//   const res = []

//   routes.forEach(route => {
//     const tmp = { ...route }
//     if (hasPermission(roles, tmp)) {
//       if (tmp.children) {
//         tmp.children = filterAsyncRoutes(tmp.children, roles)
//       }
//       res.push(tmp)
//     }
//   })

//   return res
// }

const getDefaultState = () => {
  return {
    routes: [],  // 全部路由信息（constantRoutes + myAsyncRoutes）
    addRoutes: [],  // 用户后台获取的路由信息
    permissions: []  // 用户后台获取的按钮权限
  }
}

const state = getDefaultState()

const getters = {
  routes: state => state.routes,
  addRoutes: state => state.addRoutes,
  permissions: state => state.permissions
}

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_ROUTES: (state, routes) => {
    state.routes = constantRoutes.concat(routes)  // 合并开放路由和后台获取的路由
    state.addRoutes = routes  // 保存后台获取的路由

    console.log(state.routes, '全部路由')
    console.log(state.addRoutes, '后台获取可访问路由')
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  }
}

// 替换route对象对象中的component 函数
function replaceComponent(comp) {
  // 当有compoent时
  if (comp.component && typeof (comp.component) == 'string') {
    comp.component = componentMap[comp.component]
  }

  // 判断路由中是否有children属性
  if (comp.children && comp.children.length > 0) {
    for (let i = 0; i < comp.children.length; i++) {
      comp.children[i] = replaceComponent(comp.children[i])
    }
  }
  return comp
}

const actions = {
  // 获取用户路由
  generateRoutes({commit, state}) {

    return new Promise(async resolve => {
      // 后台获取路由信息
      let {result: myAsyncRoutes} = await getRoutes()
      // 处理后台返回数据，按照vue-route的格式处理
      let arr = []
      myAsyncRoutes.forEach((item, index) => {
        // 先处理children属性
        let children = item.children

        children.forEach((child, i) => {
          children[i] = {
            path: '/' + item.router + '/' + child.router,
            component: '/' + item.router + '/' + child.router,
            name: item.router + '/' + child.router,
            meta: {
              title: child.name,
              icon: child.icon
            },
          }
        })

        let obj = {
          path: '/' + item.router,
          name: item.router,
          component: 'layout',
          redirect: item.children[0] ? item.children[0].path : '/index',
          alwaysShow: true,
          meta: {
            title: item.name,
            icon: item.icon
          },
          children
        }

        arr.push(obj)
      })
      // 调用函数整理（替换组件名称，删除空的children）
      arr = arr.filter(item => {
        // 如果children为空或者长度为0 删除children
        if (item.children == null || item.children.length == 0) {
          delete item.children
        }
        // 调用整理函数并把值返回出去
        return replaceComponent(item)
      })

      // 添加404重定向页面
      let notFindObj = {
        path: '*',
        redirect: '/404',
        hidden: true
      }
      arr.push(notFindObj)

      // 调用方法,存储可以访问的路由信息
      commit('SET_ROUTES', arr)

      resolve(arr)
    })

  },
  // 获取按钮权限信息
  generatePermissions({commit, state}) {
    return new Promise(async resolve => {

      let {result: myPermission} = await getPermissions()

      // 调用方法,存储可以操作的权限按钮
      commit('SET_PERMISSIONS', myPermission)

      resolve(myPermission)
    })
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
